import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:im_module/common/GroupCommonType.dart';
import 'package:im_module/common/hexToColor.dart';
import 'package:im_module/common/message_cache_key.dart';
import 'package:im_module/common/time_message.dart';
import 'package:im_module/manager/ImChatManager.dart';
import 'package:im_module/message/type/GroupTipsMessageWidget.dart';
import 'package:im_module/message/type/ImageMessageWidget.dart';
import 'package:im_module/message/type/LocationMessageWidget.dart';
import 'package:im_module/widget/ImHeadImageWidget.dart';
import 'package:tencent_im_sdk_plugin/enum/message_elem_type.dart';
import 'package:tencent_im_sdk_plugin/enum/message_status.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_image.dart';
import 'package:tencent_im_sdk_plugin/models/v2_tim_message.dart';

class MessageBody extends StatelessWidget {
  V2TimMessage v2timMessage;
  TextDirection? textDirection;
  int position;
  bool showTime;

  MessageBody(this.v2timMessage, this.position, this.showTime) {
    if (v2timMessage.isSelf!) {
      textDirection = TextDirection.rtl;
    } else {
      textDirection = TextDirection.ltr;
    }
  }

  String getMessageTime() {
    String time = '';
    int timestamp = v2timMessage.timestamp! * 1000;
    DateTime timeDate = DateTime.fromMillisecondsSinceEpoch(timestamp);
    DateTime now = DateTime.now();

    if (now.day == timeDate.day) {
      time =
          "${timeDate.hour.toString().padLeft(2, '0')}:${timeDate.minute.toString().padLeft(2, '0')}:${timeDate.second.toString().padLeft(2, '0')}";
    } else {
      time =
          "${timeDate.month.toString().padLeft(2, '0')}-${timeDate.day.toString().padLeft(2, '0')} ${timeDate.hour.toString().padLeft(2, '0')}:${timeDate.minute.toString().padLeft(2, '0')}:${timeDate.second.toString().padLeft(2, '0')}";
    }
    return time;
  }

  @override
  Widget build(BuildContext context) {
    //print("聊天消息:${v2timMessage.toJson()}");
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 15, vertical: 10),
      child: Column(
        children: [
          Offstage(
              offstage: !showTime,
              child: Padding(
                padding: const EdgeInsets.symmetric(vertical: 15),
                child: Text(
                  "${MessageTimeUtils.getMessageTime(v2timMessage.timestamp)}",
                  style: TextStyle(color: Color(0xff999999), fontSize: 12),
                ),
              )),
          LayoutBuilder(
            builder: (context, constraints) {
              if (v2timMessage.elemType ==
                  MessageElemType.V2TIM_ELEM_TYPE_GROUP_TIPS) {
                //群提示消息
                return GroupTipsMessageWidget(v2timMessage.groupTipsElem!);
              } else if (v2timMessage.sender ==
                      GroupCommonType.SENDER_TIM_USER &&
                  v2timMessage.elemType ==
                      MessageElemType.V2TIM_ELEM_TYPE_CUSTOM) {
                //自定义的提示消息
                return Text("${v2timMessage.customElem?.data}",
                    style: TextStyle(color: Color(0xff999999), fontSize: 14));
              } else {
                return Row(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  textDirection: textDirection,
                  children: [
                    /*CircleAvatar(
                      backgroundImage: NetworkImage("${v2timMessage.faceUrl!}"),
                      radius: 25.0,
                    ),*/
                    ImHeadImageWidget("${v2timMessage.faceUrl}"),
                    Center(
                      child: Row(
                        textDirection: textDirection,
                        crossAxisAlignment: CrossAxisAlignment.center,
                        children: [
                          Container(
                            margin:
                                EdgeInsets.only(top: 3, left: 10, right: 10),
                            constraints: BoxConstraints(
                              maxWidth:
                                  MediaQuery.of(context).size.width * 0.64,
                            ),
                            child: Container(
                              child: LayoutBuilder(
                                builder: (BuildContext context,
                                    BoxConstraints constraints) {
                                  switch (v2timMessage.elemType) {
                                    case MessageElemType.V2TIM_ELEM_TYPE_TEXT:
                                      return Container(
                                          decoration: BoxDecoration(
                                              color: v2timMessage.isSelf!
                                                  ? hexToColor('3393FF')
                                                      .withOpacity(1)
                                                  : hexToColor('ffffff')
                                                      .withOpacity(1),
                                              borderRadius: BorderRadius.only(
                                                  topLeft: v2timMessage.isSelf!
                                                      ? Radius.circular(10)
                                                      : Radius.circular(0),
                                                  bottomLeft:
                                                      Radius.circular(10),
                                                  bottomRight:
                                                      Radius.circular(10),
                                                  topRight: v2timMessage.isSelf!
                                                      ? Radius.circular(0)
                                                      : Radius.circular(10)),
                                              boxShadow: [
                                                BoxShadow(
                                                    color: Colors.black12,
                                                    offset: Offset(0.0, 10.0),
                                                    //阴影xy轴偏移量
                                                    blurRadius: 3.0,
                                                    //阴影模糊程度
                                                    spreadRadius: 1.0 //阴影扩散程度
                                                    )
                                              ]),
                                          child: buildTextMessage());
                                    case MessageElemType.V2TIM_ELEM_TYPE_IMAGE:
                                      return ImageMessageWidget(v2timMessage);
                                    case MessageElemType
                                        .V2TIM_ELEM_TYPE_LOCATION:
                                      return LocationMessageWidget(
                                          v2timMessage);
                                    case MessageElemType.V2TIM_ELEM_TYPE_CUSTOM:
                                      return Text(
                                          "${v2timMessage.customElem?.data}");
                                    default:
                                      return SizedBox();
                                  }
                                },
                              ),
                            ),
                          ),
                          getHandleBar(),
                        ],
                      ),
                    )
                  ],
                );
              }
            },
          ),
        ],
      ),
    );
  }

  Widget buildTextMessage() {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 10, horizontal: 15),
      child: Text(
        "${v2timMessage.textElem?.text}",
        style: TextStyle(
          color: v2timMessage.isSelf!
              ? hexToColor('ffffff')
              : hexToColor('000000'),
          fontSize: 16,
        ),
      ),
    );
  }

  Widget buildImageMessage() {
    print("${v2timMessage.imageElem?.imageList}");

    String? path = v2timMessage.imageElem?.path;

    List<V2TimImage?>? urls = v2timMessage.imageElem?.imageList;

    if (path == null || path.isEmpty) {
      path = urls?.where((element) => element!.type == 2).single?.url;
    }

    if (!path!.startsWith('http')) {
      return Container(
        constraints: BoxConstraints(
          maxHeight: 100,
          maxWidth: 100,
        ),
        child: Image.file(
          new File("${v2timMessage.imageElem!.path}"),
        ),
      );
    } else {
      return Container(
        constraints: BoxConstraints(
          maxHeight: 100,
          maxWidth: 100,
        ),
        child: Image.network(
          "$path",
        ),
      );
    }
  }

  Widget getHandleBar() {
    Widget wid = new Container();
    V2TimMessage msgobj = v2timMessage;
    if (msgobj.isSelf!) {
      //发送成功
      if (msgobj.status == MessageStatus.V2TIM_MSG_STATUS_SEND_SUCC) {
        if (msgobj.isPeerRead! &&
            (msgobj.groupID == null || msgobj.groupID == '')) {
          //c2c消息已读
          wid = Text(
            "已读",
            style: TextStyle(
              fontSize: 10,
              color: Color(0xff666666),
            ),
          );
        }
        if (msgobj.isPeerRead == false &&
            (msgobj.groupID == null || msgobj.groupID == '')) {
          //c2c未读
          wid = Text(
            "未读",
            style: TextStyle(
              fontSize: 10,
              color: Colors.red,
            ),
          );
        }
      }
      //发送失败
      if (msgobj.status == MessageStatus.V2TIM_MSG_STATUS_SEND_FAIL) {
        wid = Row(
          mainAxisAlignment: MainAxisAlignment.end,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Icon(
              Icons.info,
              size: 14,
              color: Colors.red,
            ),
            Text(
              "发送失败",
              style: TextStyle(
                fontSize: 10,
                color: Colors.red,
                height: 1.4,
              ),
            ),
            Container(
              margin: EdgeInsets.only(left: 5),
              child: InkWell(
                onTap: () {
                  if (msgobj.userID != null) {
                    ImChatManager().reSendMessage(
                        MessageCacheKey.getC2cKey("${msgobj.userID}"),
                        msgobj.msgID!);
                  } else if (msgobj.groupID != null) {
                    ImChatManager().reSendMessage(
                        MessageCacheKey.getGroupKey("${msgobj.groupID}"),
                        msgobj.msgID!);
                  }
                },
                child: Text(
                  "重新发送",
                  style: TextStyle(
                    fontSize: 10,
                    color: Colors.blue,
                    height: 1.4,
                  ),
                ),
              ),
            )
          ],
        );
      }
      //发送中
      if (msgobj.status == MessageStatus.V2TIM_MSG_STATUS_SENDING) {
        wid = Text(
          "发送中...",
          style: TextStyle(
            fontSize: 10,
            color: Colors.black26,
          ),
        );
      }
    }
    // 非自己消息不作处理
    return wid;
  }
}
